package com.jintian.hnsj_metting.util;

import android.text.TextUtils;

import com.hikvision.smarteyes.utils.log.DFLog;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * 〈一句话功能简述〉
 * 〈功能详细描述〉
 *
 * @author weixuewu
 * @version 1.0, 2019/12/6
 * @since 产品模块版本
 */
public class CrashUtil implements Thread.UncaughtExceptionHandler{

    private String logFilePath = "/log/smartEyes/";

    @Override
    public void uncaughtException(Thread t, Throwable e) {
//        Log.e("程序出现异常了", "Thread = " + t.getName() + "\nThrowable = " + e.getMessage());
        String stackTraceInfo = getStackTraceInfo(e);
        DFLog.e("stackTraceInfo", stackTraceInfo);
        saveThrowableMessage(stackTraceInfo);
        //调用系统API结束进程
        android.os.Process.killProcess(android.os.Process.myPid());
    }
    /**
     * 获取错误的信息
     *
     * @param throwable
     * @return
     */
    private String getStackTraceInfo(final Throwable throwable) {
        PrintWriter pw = null;
        Writer writer = new StringWriter();
        try {
            pw = new PrintWriter(writer);
            throwable.printStackTrace(pw);
        } catch (Exception e) {
            return "";
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
        return writer.toString();
    }



    private void saveThrowableMessage(String errorMessage) {
        if (TextUtils.isEmpty(errorMessage)) {
            return;
        }
        File file = new File(logFilePath);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (mkdirs) {
                writeStringToFile(errorMessage, file);
            }
        } else {
            writeStringToFile(errorMessage, file);
        }
    }

    private void writeStringToFile(final String errorMessage, final File file) {
        FileOutputStream outputStream = null;
        try {
            File file1 = new File(file, "demo_crash.txt");
            if (!file1.exists()) {
                file1.createNewFile();
            } else {
                if (file1.length() > 1024 * 1024) {
                    file1.delete();
                    file1.createNewFile();
                }
            }
            ByteArrayInputStream inputStream = new ByteArrayInputStream(errorMessage.getBytes());
            outputStream = new FileOutputStream(file1, true);
            String time = getIOS8601Time();
            outputStream.write("\n\n\n".getBytes());
            outputStream.write(time.getBytes());
            outputStream.write("\n".getBytes());
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取ISO8601格式时间
     * 例如：2004-05-03T17:30:08+08:00
     * @return ISO8601时间
     */
    public static String getIOS8601Time(){
        TimeZone tz = TimeZone.getDefault();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        dateFormat.setTimeZone(tz);
        Date data = Calendar.getInstance().getTime();
        return dateFormat.format(data);
    }
}
